#include "unitwindow.h"
#include "ui_unitwindow.h"

UnitWidget::UnitWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UnitWidget)
{
    ui->setupUi(this);
    boolTcp = false;
    initDatabase();
    //initTcp();
    connect(ui->specialButton, SIGNAL(clicked()), this, SLOT(newDatabase()));
}

UnitWidget::~UnitWidget()
{
    delete ui;
}

void UnitWidget::updateInfo(const UnitData &data)
{

}
void UnitWidget::storeMessage(QByteArray message)
{
    //store message in class data
    //qDebug() << "MSG RX" << message;
    int commacounter = 0;
    QByteArray tempmsg;
    UnitData datamessage;
    for(int i = 0; i < message.count(); i++)
    {
        if (message.at(i) != 0x2C)
        {
            tempmsg.append(message.at(i));
        }
        else  if (message.at(i) == 0x2C)
        {
            commacounter++;
            switch(commacounter)
            {
            case 1:
                datamessage.unit_id = QString(tempmsg);
                break;
            case 2:
                datamessage.accel_x = QString(tempmsg);
                break;
            case 3:
                datamessage.accel_y = QString(tempmsg);
                break;
            case 4:
                datamessage.accel_z = QString(tempmsg);
                break;
            case 5:
                datamessage.accel_temp = QString(tempmsg);
                break;
            case 6:
                datamessage.unit_pressure = QString(tempmsg);
                break;
            case 7:
                datamessage.unit_temp = QString(tempmsg);
                break;
            case 8:
                datamessage.bpm_instant = QString(tempmsg);
                break;
            case 9:
                datamessage.bpm_average = QString(tempmsg);
                break;
            case 10:
                datamessage.unit_rssifreq = QString(tempmsg);
                break;
            case 11:
                datamessage.unit_rssiduty = QString(tempmsg);
                break;
            case 12:
                datamessage.adc_1 = QString(tempmsg);
                break;
            case 13:
                datamessage.adc_2 = QString(tempmsg);
                break;
            case 14:
                //datamessage.adc_3 = QString(tempmsg);
                datamessage.unit_checksum = QString(tempmsg);
                break;
            case 15:
                //datamessage.adc_4 = QString(tempmsg);
                datamessage.base_checksum = QString(tempmsg);
                break;
            case 16:
                //datamessage.unit_checksum = QString(tempmsg);
                datamessage.base_pressure = QString(tempmsg);
                break;
            case 17:
                //datamessage.base_checksum = QString(tempmsg);
                datamessage.base_temp = QString(tempmsg);
                break;
            case 18:
                //datamessage.base_pressure = QString(tempmsg);
                datamessage.rssi_1 = QString(tempmsg);
                break;
            case 19:
                //datamessage.base_temp = QString(tempmsg);
                datamessage.rssi_2 = QString(tempmsg);
                break;
            case 20:
                //datamessage.rssi_1 = QString(tempmsg);
                datamessage.rssi_3 = QString(tempmsg);
                break;
            case 21:
                //datamessage.rssi_2 = QString(tempmsg);
                datamessage.rssi_4 = QString(tempmsg);
            break;
            case 22:
                //datamessage.rssi_3 = QString(tempmsg);
                datamessage.rssi_avgcount = QString(tempmsg);
                break;
            /* MISSING THESE 2 CASES
               ALL OTHERS SHIFTED BACK BECAUSE OF 2 MISSING ADC VALUES
            case 23:
                datamessage.rssi_4 = QString(tempmsg);
                break;
            case 24:
                datamessage.rssi_avgcount = QString(tempmsg);
                break;
            */
            default:
                break;
            }
            tempmsg.clear();
        }
    }
    //validate here??
    insertDatabase(datamessage);
    //sendTcp(datamessage);

}
void UnitWidget::initDatabase()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("WALK5.db3");
    tablecounter = 0;
    tablename = "data";
    tablename.append(QString::number(tablecounter));
    if (!db.open()) {
         QMessageBox::critical(0, tr("Cannot open database"),
             tr("Unable to establish a database connection.\n"
                "This example needs SQLite support. Please read "
                "the Qt SQL driver documentation for information how "
                "to build it."), QMessageBox::Cancel);
         return;
     }
    QSqlQuery query;
    query.prepare("create table " + tablename + " (id integer primary key, "
                                  "unitid int, acc_x int, acc_y int, acc_z int, acc_temp int, "
                                  "unit_pressure int, unit_temp int, bpm_instant int, bpm_average int, "
                                  "unit_rssifreq int, unit_rssiduty int, adc_1 int, adc_2 int, unit_checksum int, "
                                  "base_checksum int, base_pressure int, base_temp int, "
                                  "rssi_1 int, rssi_2 int, rssi_3 int, rssi_4 int, rssi_avg int) "
                                  );
    query.exec();
    qDebug() << tablename;
    tablecounter++;
    databaseset = true;
}
void UnitWidget::newDatabase()
{
    tablename = "data";
    tablename.append(QString::number(tablecounter));
    if (!db.open()) {
         QMessageBox::critical(0, tr("Cannot open database"),
             tr("Unable to establish a database connection.\n"
                "This example needs SQLite support. Please read "
                "the Qt SQL driver documentation for information how "
                "to build it."), QMessageBox::Cancel);
         return;
     }
    QSqlQuery query;
    query.prepare("create table " + tablename + " (id integer primary key, "
                                  "unitid int, acc_x int, acc_y int, acc_z int, acc_temp int, "
                                  "unit_pressure int, unit_temp int, bpm_instant int, bpm_average int, "
                                  "unit_rssifreq int, unit_rssiduty int, adc_1 int, adc_2 int, unit_checksum int, "
                                  "base_checksum int, base_pressure int, base_temp int, "
                                  "rssi_1 int, rssi_2 int, rssi_3 int, rssi_4 int, rssi_avg int) "
                                  );
    query.exec();
    qDebug() << tablename;
    tablecounter++;

}
void UnitWidget::insertDatabase(UnitData insertdata)
{
    if (databaseset)
    {
        QSqlQuery query;
                   query.prepare("insert into " + tablename + " (id, unitid, acc_x, acc_y, acc_z, acc_temp, "
                                                   "unit_pressure, unit_temp, bpm_instant, bpm_average, "
                                                   "unit_rssifreq, unit_rssiduty, adc_1, adc_2, unit_checksum, base_checksum, "
                                                   "base_pressure, base_temp, rssi_1, rssi_2, rssi_3, "
                                                   "rssi_4, rssi_avg ) "
                                 "values (NULL,  :unitid, :acc_x, :acc_y, :acc_z, :acc_temp, "
                                          ":unit_pressure, :unit_temp, :bpm_instant, :bpm_average, "
                                          ":unit_rssifreq, :unit_rssiduty, :adc_1, :adc_2, :unit_checksum, :base_checksum, "
                                          ":base_pressure, :base_temp, :rssi_1, :rssi_2, :rssi_3, "
                                          ":rssi_4, :rssi_avg ) "
                                 );
                   //query.bindValue(":name", tablename);
                   query.bindValue(":unitid", insertdata.unit_id.toInt());
                   query.bindValue(":acc_x", insertdata.accel_x.toInt());
                   query.bindValue(":acc_y", insertdata.accel_y.toInt());
                   query.bindValue(":acc_z", insertdata.accel_z.toInt());
                   query.bindValue(":acc_temp", insertdata.accel_temp.toInt());
                   query.bindValue(":unit_pressure", insertdata.unit_pressure.toInt());
                   query.bindValue(":unit_temp", insertdata.unit_temp.toInt());
                   query.bindValue(":bpm_instant", insertdata.bpm_instant.toInt());
                   query.bindValue(":bpm_average", insertdata.bpm_average.toInt());
                   query.bindValue(":unit_rssifreq", insertdata.unit_rssifreq.toInt());
                   query.bindValue(":unit_rssiduty", insertdata.unit_rssiduty.toInt());
                   query.bindValue(":adc_1", insertdata.adc_1.toInt());
                   query.bindValue(":adc_2", insertdata.adc_2.toInt());
                   query.bindValue(":unit_checksum", insertdata.unit_checksum.toInt());
                   query.bindValue(":base_checksum", insertdata.base_checksum.toInt());
                   query.bindValue(":base_pressure", insertdata.base_pressure.toInt());
                   query.bindValue(":base_temp", insertdata.base_temp.toInt());
                   query.bindValue(":rssi_1", insertdata.rssi_1.toInt());
                   query.bindValue(":rssi_2", insertdata.rssi_2.toInt());
                   query.bindValue(":rssi_3", insertdata.rssi_3.toInt());
                   query.bindValue(":rssi_4", insertdata.rssi_4.toInt());
                   query.bindValue(":rssi_avg", insertdata.rssi_avgcount.toInt());
                   if(!query.exec())
                   {
                       qDebug() << "failed to execute";
                        qDebug() << query.lastError();
                   }


    }
}
void UnitWidget::sendTcp(UnitData senddata)
{
    /*
    if (boolTcp)
    {
       // QTcpSocket *clientConnect = tcpServer->

        query.bindValue(":unitid", senddata.unit_id.toInt());
        query.bindValue(":acc_x", senddata.accel_x.toInt());
        query.bindValue(":acc_y", senddata.accel_y.toInt());
        query.bindValue(":acc_z", senddata.accel_z.toInt());
        query.bindValue(":acc_temp", senddata.accel_temp.toInt());
        query.bindValue(":unit_pressure", senddata.unit_pressure.toInt());
        query.bindValue(":unit_temp", senddata.unit_temp.toInt());
        query.bindValue(":bpm_instant", senddata.bpm_instant.toInt());
        query.bindValue(":bpm_average", senddata.bpm_average.toInt());
        query.bindValue(":unit_rssifreq", senddata.unit_rssifreq.toInt());
        query.bindValue(":unit_rssiduty", senddata.unit_rssiduty.toInt());
        query.bindValue(":adc_1", senddata.adc_1.toInt());
        query.bindValue(":adc_2", senddata.adc_2.toInt());
        query.bindValue(":unit_checksum", senddata.unit_checksum.toInt());
        query.bindValue(":base_checksum", senddata.base_checksum.toInt());
        query.bindValue(":base_pressure", senddata.base_pressure.toInt());
        query.bindValue(":base_temp", senddata.base_temp.toInt());
        query.bindValue(":rssi_1", senddata.rssi_1.toInt());
        query.bindValue(":rssi_2", senddata.rssi_2.toInt());
        query.bindValue(":rssi_3", senddata.rssi_3.toInt());
        query.bindValue(":rssi_4", senddata.rssi_4.toInt());
        query.bindValue(":rssi_avg", senddata.rssi_avgcount.toInt());

    }
    */
}

void UnitWidget::initTcp()
{
    tcpServer = new QTcpServer(this);
         if (!tcpServer->listen()) {
             QMessageBox::critical(this, tr("Fortune Server"),
                                   tr("Unable to start the server: %1.")
                                   .arg(tcpServer->errorString()));
             close();
             return;
         }
         QString ipAddress;
         QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
         // use the first non-localhost IPv4 address
         for (int i = 0; i < ipAddressesList.size(); ++i) {
             if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
                 ipAddressesList.at(i).toIPv4Address()) {
                 ipAddress = ipAddressesList.at(i).toString();
                 break;
             }
         }
         // if we did not find one, use IPv4 localhost
         if (ipAddress.isEmpty())
             ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
         QString serverup = (tr("The server is running on\n\nIP: %1\nport: %2\n\n")
                              .arg(ipAddress).arg(tcpServer->serverPort()));
         qDebug() << serverup;
        connect(tcpServer, SIGNAL(newConnection()), this, SLOT(tcpOpen()));
}

void UnitWidget::tcpOpen()
{
    boolTcp = true;
}

